package com.hzcx.app.simplechat.util.app;


import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.res.Resources;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.core.content.FileProvider;

import com.hyphenate.chat.EMTextMessageBody;
import com.hzcx.app.simplechat.MyApplication;
import com.hzcx.app.simplechat.event.FinishEvent;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static android.content.Context.CLIPBOARD_SERVICE;

public class AppHelper {

    /**
     * 双击退出程序
     */
    private static boolean isBack = false;

    public static void backFinish() {
        if (!isBack) {
            ToastUtils.show("在按一次退出程序");
            isBack = true;
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    isBack = false;
                }
            }, 2000);
        } else {
            EventBus.getDefault().post(new FinishEvent());
        }
    }

    /**
     * 获取版本名称
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return "v" + packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取版本名称
     *
     * @param context
     * @return
     */
    public static String getVersionCode(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode + "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 弹出软键盘
     *
     * @param view
     */
    public static void showSoftKeyboard(View view, Context context) {

        view.postDelayed(() -> {
            view.requestFocus();
            InputMethodManager manager = ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE));
            if (manager != null) manager.showSoftInput(view, 0);
        }, 100);

    }

    /**
     * 隐藏软键盘
     *
     * @param view
     * @param mContext
     */
    public static void closeSoftKeybord(View view, Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    /**
     * 讲手机号码中间替换为*
     *
     * @param phone
     * @return
     */
    public static String hidePhone(String phone) {
        try {
            return phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 复制文本
     *
     * @param context
     * @param content
     */
    public static void copy(Context context, String content) {
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);
        clipboard.setPrimaryClip(ClipData.newPlainText(null, content));
    }


    /**
     * 判断应用是否在前台
     *
     * @param context
     * @return
     */
    public static boolean isBackground(Context context) {
        if (context == null) {
            return false;
        }
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        boolean isBackground = true;
        String processName = "empty";
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                processName = appProcess.processName;
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED) {
                    isBackground = true;
                } else if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                        || appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
                    isBackground = false;
                } else {
                    isBackground = true;
                }
            }
        }
        if (isBackground) {
            Log.d("simpleChat", "后台:" + processName);
        } else {
            Log.d("simpleChat", "前台+" + processName);
        }
        return isBackground;
    }

    /**
     * 获取系统剪贴板内容
     */
    public static String getClipContent() {
        try {
            ClipboardManager manager = (ClipboardManager) MyApplication.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
            if (manager != null&&manager.getPrimaryClip()!=null) {
                if (manager.hasPrimaryClip() && manager.getPrimaryClip().getItemCount() > 0) {
                    CharSequence addedText = manager.getPrimaryClip().getItemAt(0).getText();
                    String addedTextString = String.valueOf(addedText);
                    if (!TextUtils.isEmpty(addedTextString)) {
                        return addedTextString;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    public static String gangUpInvite(final Context context) {
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);
        //无数据时直接返回
        if (!clipboard.hasPrimaryClip()) {
            LogUtils.d("没有复制的文本");
            return null;
        }
        //如果是文本信息
        if (clipboard.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
            ClipData cdText = clipboard.getPrimaryClip();
            ClipData.Item item = cdText.getItemAt(0);
            //此处是TEXT文本信息
            if (item.getText() != null) {
                String str = item.getText().toString();
                LogUtils.d("str:" + str);
                String key = "*";
                final int first = str.indexOf(key);
                if (first >= 0) {
                    String new1 = str.substring(first + 1);
                    int tow = new1.indexOf(key);
                    if (tow >= 0) {
                        String new2 = new1.substring(0, tow);
                        if (new2.length() == 8) {
                            //new2即为口令字符串
                            return new2;
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 安装APK
     *
     * @param context
     * @param path
     */
    public static void installApk(Context context, String path) {
        File apk = new File(path);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri uri = FileProvider.getUriForFile(context, "com.hzcx.app.simplechat.fileProvider", apk);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }
}
